/******
 * Javascript library for irods plugin metadata services
 *
 * Author: Mike Conway - RENCI (www.renci.org)
 * Date: 07/22/2009
 *
 * TODO: error handling...create display in irods.xml as standard message area, need to account for several errors that are transmitted
 * 	by enginframe in response pages....what other?
 */

// reference to datatab
var dataTab;


/*
 * initialize the text box on the metadata form with metadata attribute names, based on the type
 * (user, coll, and data for user, data object, and collection per the iRODS imeta function).
 *
 * @parm metaType - user, coll, or data
 *
 */
function initMetaDataSubjectAutocomplete(metaType) {

	try {
		if (metaType == "user") {
			$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_user_meta_attribute_names", function(data) { buildAutocompleteWithPredicate(data)}, "text");
		} else if (metaType == "coll") {
			$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_coll_meta_attribute_names", function(data) { buildAutocompleteWithPredicate(data)}, "text");
		} else if (metaType == "data") {
			$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_data_meta_attribute_names", function(data) { buildAutocompleteWithPredicate(data)}, "text");
		} else {
			throw "invalid metaType:" + metaType;
		}
	} catch (err) {
		//console.trace();
		//console.log("error in initMetaDataSubjectAutocomplete:" + err);
	}
}

/*
 * Function for AJAX callbacks that parses out data from enginFrame and sets the autocomplete of the 'metadataPredicate' box
 * with the incoming data.  Callback is used in initMetaDataSubjectAutocomplete(metaType) function;
 *
 * @param data - raw data from the enginframe service call
 * @return void
 */
function buildAutocompleteWithPredicate(data) {
	
	var errDat = checkAppError(data);
	if (errDat.status == "E") {
		// FIXME: console traces are not good for IE - mcc
		//console.trace();
		//console.log("error in buildAutoCompleteWithPredicate:" + errDat.errorMinor);
		throw errDat.errorMinor;
	} 
	
	var serviceData = data.substring((data.indexOf("##START##") + 9), data.indexOf("##END##"));
	var predicates = new Array();
	predicates = serviceData.split("|");
	$("#metadataPredicate").autocomplete(predicates).focus();
}

/*********
 * Called from button on web page, interrogates the type of metadata to be found (user, data, collection)
 * and formulates the correct service call to the headless service that accesses irods.  Will
 * set the proper callback function for the data (e.g. a user metadata selection wsill call buildUserListFromMetaData function.
 *
 * @return - void
 */

function getMetaData() {

	$("#metaDataResult")
		.html("<img src='images/loading.gif'>&nbsp;&nbsp;Fetching data from iRODS, please wait...");

	var metaType = $("#metadataSubjectType").val();
	// TODO: look at query behavior, does not seem to be able to differentiate between different metadata types - mcc
	try {
		if (metaType == "user") {
			$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_user_metadata_search_list&_meta_user_attr_name=" + escape($("#metadataPredicate").val()) + "&_meta_user_attr_value=" + escape($("#metadataValue").val()) , function(data) { buildUserListFromMetaData(data)}, "text");
		} else if (metaType == "coll") {
			$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_coll_metadata_search_list&_meta_coll_attr_name=" + escape($("#metadataPredicate").val()) + "&_meta_coll_attr_value=" + escape($("#metadataValue").val()), function(data) { buildCollListFromMetaData(data)}, "text");
		} else if (metaType == "data") {
			$.get("irods.xml?_uri=//com.enginframe.irods.metadata/get_data_metadata_search_list&_meta_data_attr_name=" + escape($("#metadataPredicate").val()) + "&_meta_data_attr_value=" + escape($("#metadataValue").val()), function(data) { buildDataListFromMetaData(data)}, "text");
		} else {
			throw "invalid metaType:" + metaType;
		}
	} catch (err) {
		// FIXME: console traces are not good for IE - mcc
		//console.trace();
		//console.log("error in getMetaData():" + err);
	}

}

/*************
 * Function called by ajax action as response handler.  Builds the data table
 *
 * @param data - results from ajax call in | delimited format for parsin
 * @return - void
 */
function buildUserListFromMetaData(data) {

	
	var output = "";
	
	var errDat = checkAppError(data);
	if (errDat.status == "E") {
	//	console.trace();
	//	console.log("error in buildAutoCompleteWithPredicate:" + errDat.errorMinor);
		throw errDat.errorMinor;
	} 
	
	var coreData = data.substring((data.indexOf("##START##") + 9),
			data.indexOf("##END##"));
	var items = coreData.split("\n");

	output += "<div id='metaDataTableContainer'><table cellpadding='5' cellspacing='0' id='tabularData' class='list-table'><thead>";
	output += "<tr class='lt-header'>";
	output += "<th class='lt-header-field'>User name</th>";
	output += "<th class='lt-header-field'>User type</th>";
	output += "<th class='lt-header-field'>User zone</th>";
	output += "<th class='lt-header-field'>Attrib name</th>";
	output += "<th class='lt-header-field'>Attrib value</th>";
	

	output += "</tr></thead><tbody>";

	var expandDiv = "";

	for ( var i = 0; i < (items.length); i++) {
		var tokens = items[i].split("|");

		if (tokens.length > 1) {

			output += "<tr class='lt-row'>";
			output += "<td class='lt-field' id='tr-" + trim(tokens[5])
					+ "'>"
					+ tokens[6] + "</td>";
			output += "<td class='lt-field'>" + tokens[7]
					+ "</td>";
			output += "<td class='lt-field'>"
					+ [tokens[8]] + "</td>";
			output += "<td class='lt-field'>"
					+ [tokens[1]] + "</td>";
			output += "<td class='lt-field'>" + tokens[2] + " <b>" + tokens[3]
					+ "</b></td></tr>";
		}
	}

	output += "</tbody></table></div>";
	$("#metaDataResult").html(output);
	dataTab = $("#tabularData").dataTable( {
		"bAutoWidth" :true,
		"bSortClasses" :true,
		// TODO: table expansion code temporarily removed - mcc
//		"aoColumns": [
//		  			{ "bSortable": false },
//		  			null, null, null, null,
//		  		],
  		"aaSorting": [[1, 'asc']],
		oLanguage : {
			"sSearch" :"Filter:"
		}
	});

	/* Add event listener for opening and closing details
	 * Note that the indicator for showing which row is open is not controlled by DataTables,
	 * rather it is done here
	 * TODO: temporarily removed, potentially add functionality later - mcc
	 */

//	$('td .ui-icon-circle-plus', dataTab.fnGetNodes() ).each( function () {
//		$(this).click( function () {
//			var nTr = this.parentNode.parentNode;
//
//			if ( this.className.match("ui-icon-circle-plus"))
//			{
//
//				this.className = "ui-icon ui-icon-circle-minus";
//				//dataTab.fnOpen( nTr, formatUserDetails(nTr), 'details' );
//				dataTab.fnOpen( nTr, "<h1>Hi There</h1>", "details" );
//			}
//			else
//			{
////				// close row
////
////				//alert("closing:" + nTr);
//				dataTab.fnClose( nTr );
//				this.className = "ui-icon ui-icon-circle-plus";
//			}
//		} );
//	} );

}

/**************************************************
 * metadata display table formatting code
 *
 **************************************************/

/******
 * Formatting function for expandable row details in user metadata results table
 *
 * @param nTr - <TR> node in table under which the 'details' will expand
 * @return void
 */
function formatUserDetails ( nTr )
{

	var iIndex = dataTab.fnGetPosition( nTr );
	var aData = dataTab.fnSettings().aoData[iIndex]._aData;

	// get the comment and info for this user to plug into the table data

	var userId = nTr.id;
	var sOut = '<table cellpadding="5" cellspacing="0" border="0"><tbody>';
	sOut += '<tr><td>Info:</td><td>' + aData[4] + '</td></tr>';
	sOut += '<tr><td>User Comment:</td><td>User comment here</td></tr>';
	sOut += '</tbody></table>';

	return sOut;
}

/***********
 * Build (via an ajax call to an enginFrame service) a table containing the data objects with
 * the selected metadata attributes.  This method will be supplied as a callback to the actual ajax call.
 *
 * @param data - | delimited data from a query to the irods icat.
 * @return null
 */
function buildDataListFromMetaData(data) {

	
	var output = "";
	
	var errDat = checkAppError(data);
	if (errDat.status == "E") {
		//console.trace();
		//console.log("error in buildAutoCompleteWithPredicate:" + errDat.errorMinor);
		throw errDat.errorMinor;
	} 

	var coreData = data.substring((data.indexOf("##START##") + 9),
			data.indexOf("##END##"));
	var items = coreData.split("\n");

	output += "<div id='metaDataTableContainer'><table cellpadding='5' cellspacing='0' id='tabularData' class='list-table'><thead>";
	output += "<tr class='lt-header'>";
	output += "<th class='lt-header-field'>Data collection</th>";
	output += "<th class='lt-header-field'>Data name</th>";
	output += "<th class='lt-header-field'>Attrib name</th>";
	output += "<th class='lt-header-field'>Attrib value</th>";
	output += "</tr></thead><tbody>";

	var expandDiv = "";

	for ( var i = 0; i < (items.length); i++) {
		var tokens = items[i].split("|");

		if (tokens.length > 1) {

			output += "<tr class='lt-row' id='attr-" + trim(tokens[4]) + "'>";
			output += "<td class='lt-field'>"
					+ tokens[8] + "</td>";
			output += "<td class='lt-field'>" 
					+ tokens[6]
					+ "</td>";
			output += "<td class='lt-field'>" 
					+ tokens[1 ]
					+ "</td>";
			output += "<td class='lt-field'>" + tokens[2] + "<b>" + tokens[3]
					+ "</b></td></tr>";
		}
	}

	output += "</tbody></table></div>";
	$("#metaDataResult").html(output);
	dataTab = $("#tabularData").dataTable( {
		"bAutoWidth" :true,
		"bSortClasses" :true,
  		"aaSorting": [[1, 'asc']],
		oLanguage : {
			"sSearch" :"Filter:"
		}
	});
}

/***********
 * Build (via an ajax call to an enginFrame service) a table containing the collection objects with
 * the selected metadata attributes.  This method will be supplied as a callback to the actual ajax call.
 *
 * @param data - | delimited data from a query to the irods icat.
 * @return void
 */
function buildCollListFromMetaData(data) {

		
	var output = "";
	
	var errDat = checkAppError(data);
	if (errDat.status == "E") {
		//console.trace();
		//console.log("error in buildAutoCompleteWithPredicate:" + errDat.errorMinor);
		throw errDat.errorMinor;
	} 

	var coreData = data.substring((data.indexOf("##START##") + 9),
			data.indexOf("##END##"));
	var items = coreData.split("\n");

	output += "<div id='metaDataTableContainer'><table cellpadding='5' cellspacing='0' id='tabularData' class='list-table'><thead>";
	output += "<tr class='lt-header'>";
	output += "<th class='lt-header-field'>Coll name</th>";
	output += "<th class='lt-header-field'>Coll parent name</th>";
	output += "<th class='lt-header-field'>Attrib name</th>";
	output += "<th class='lt-header-field'>Attrib value</th>";
	output += "</tr></thead><tbody>";

	var expandDiv = "";

	for ( var i = 0; i < (items.length); i++) {
		var tokens = items[i].split("|");

		if (tokens.length > 1) {

			output += "<tr class='lt-row'>";
			output += "<td class='lt-field' id='tr-" + trim(tokens[5])
					+ "'>"
					+ tokens[6] + "</td>";
			output += "<td class='lt-field'>"
					+ tokens[7] + "</td>";
			output += "<td class='lt-field'>"
					+ tokens[1] + "</td>";
			output += "<td class='lt-field'>" + tokens[2] + " <b>" + tokens[3]
					+ "<b></td></tr>";
		}
	}

	output += "</tbody></table></div>";
	$("#metaDataResult").html(output);
	dataTab = $("#tabularData").dataTable( {
		"bAutoWidth" :true,
		"bSortClasses" :true,
  		"aaSorting": [[1, 'asc']],
		oLanguage : {
			"sSearch" :"Filter:"
		}
	});

}







